package com.jtpay.unionpay.product.dbUtils;

import android.app.Activity;
import com.jtpay.unionpay.product.DaoSession;
import com.jtpay.unionpay.product.ProductBeanDao;
import com.jtpay.unionpay.product.model.ProductBean;
import com.jtpay.unionpay.product.utils.AppApplication;
import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.WhereCondition;

/**
 * Description:
 * File: CustomDbUtils.java
 * Author: Administrator
 * Create: 2018/07/17 13:46
 */
public class CustomDbUtils {
    private ProductBeanDao productBeanDao;
    private static CustomDbUtils instance;

    public static CustomDbUtils getInstance() {
        if (instance == null) {
            instance = new CustomDbUtils();
        }
        return instance;
    }

    public void initDBUtils(Activity activity) {
        DaoSession daoSession = ((AppApplication) activity.getApplication()).getDaoSession();
        productBeanDao = daoSession.getProductBeanDao();
    }

    public synchronized void insert(ProductBean bean) {
        if (productBeanDao != null) {
            productBeanDao.insert(bean);
        }
    }

    public synchronized void update(ProductBean bean) {
        if (productBeanDao != null) {
            productBeanDao.insertOrReplace(bean);
        }
    }

    public synchronized Query<ProductBean> query(WhereCondition cond, WhereCondition... condMore) {
        if (productBeanDao != null) {
            return productBeanDao.queryBuilder().where(cond, condMore)
//                    .build();
                    .orderDesc(ProductBeanDao.Properties.Id).build();
        }
        return null;
    }

    public synchronized void delete(ProductBean bean) {
        if (productBeanDao != null) {
            productBeanDao.delete(bean);
        }
    }

    public synchronized void deleteAll() {
        if (productBeanDao != null) {
            productBeanDao.deleteAll();
        }
    }
}
